# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :user.py
# @Time      :2022/6/8 0008 19:42
# @Author    :何胜利
import random

import redis
from flask import Blueprint, jsonify, g
from flask_restful import Api, Resource, reqparse, marshal

from common.celery_tasks.send_tasks import send_code
from common.model_fields.user import *
from common.utils.jwt_util import _generate_token
from common.utils.login_utils import login_required
from common.utils.qiniu_fiel import qiniu_token
from models.user import *

user_bp = Blueprint("user_bp", __name__, url_prefix="/v1_0")

api = Api(user_bp)


# 短信验证码
class SMSCode(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument("mobile")
        args = parser.parse_args()
        mobile = args["mobile"]

        code = random.randint(1000, 9999)

        res = send_code.delay(mobile, code)
        if res:
            rdb = redis.Redis(db=4)
            rdb.set(mobile, code, ex=600)
            rdb.close()
            return jsonify(message="短信发送成功，请注意查收", code=200)
        else:
            return jsonify(message="短信发送失败", code=400)


# 登录
class LoginResource(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument("mobile")
        parser.add_argument("code")
        args = parser.parse_args()
        mobile = args["mobile"]
        code = args["code"]
        try:
            user = UserModel.query.filter_by(mobile=mobile).first()
        except Exception as e:
            print("判断手机号是否存在的错误信息", e)
            return jsonify(message="手机号未注册", code=400)
        rdb = redis.Redis(db=4)
        sms_code = rdb.get(mobile)
        if code != sms_code.decode('utf-8'):
            return jsonify(message="验证码错误", code=400)

        token, refresh_token = _generate_token({"user_id": user.uid}, is_refresh=True)
        print("refresh_token", refresh_token)
        if token:
            return jsonify(message="登录成功", code=200,
                           data={"user_id": user.uid, "token": token, "refresh_token": refresh_token})
        else:
            return jsonify(message="token生成失败", code=400)


# 频道
class ChannelResource(Resource):
    def get(self):
        channel = Channel.query.all()
        return jsonify(message="获取频道成功", code=200, data=marshal(channel, channel_fields))


# 文章
class NewsResource(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument("channel_id")
        args = parser.parse_args()
        cid = args["channel_id"]
        news = News.query.filter_by(channel_id=cid).all()
        return jsonify(message="获取文章成功", code=200, data=marshal(news, news_fields))


# 文章详情
class NewsXq(Resource):
    def get(self, nid):
        news = News.query.filter_by(nid=nid).first()
        news1 = marshal(news, news_fields)
        user = UserModel.query.filter_by(uid=news1.get("user_id")).first()

        return jsonify(message="获取成功", code=200,
                       data={"news": marshal(news, news_fields), "user": marshal(user, user_fields)})


# 获取评论
class CommentResource(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument("source")
        parser.add_argument("offset")
        args = parser.parse_args()
        article_id = args["source"]
        parent_id = args["offset"]
        comment1 = Comment.query.filter_by(article_id=article_id, parent_id=None).all()
        comment1_list = []
        for i in comment1:
            comment_ = marshal(i, comment_fields)
            print("comment_", comment_)
            comment2 = Comment.query.filter_by(parent_id=i.cmid).all()
            print("comment2", comment2)

            user1 = UserModel.query.filter_by(uid=i.user_id).first()
            comment2_list = []
            for j in comment2:
                user2 = UserModel.query.filter_by(uid=j.user_id).first()

                comment2 = marshal(j, comment_fields)
                comment2["user"] = marshal(user2, user_fields)
                comment2_list.append(comment2)
            comment_["parent"] = comment2_list
            comment_["user"] = marshal(user1, user_fields)
            comment1_list.append(comment_)
        return jsonify(message="获取评论成功", code=200, data=comment1_list)


# 发布评论
class CommentFb(Resource):
    @login_required
    def post(self):
        uid = g.user_id
        parser = reqparse.RequestParser()
        parser.add_argument("target")
        parser.add_argument("content")
        args = parser.parse_args()
        article_id = args["target"]
        content = args["content"]
        print("获取的文章id和评论内容", article_id, content)
        try:
            comment = Comment(user_id=uid, article_id=article_id, parent_id=None, content=content)
            db.session.add(comment)
            db.session.commit()
        except Exception as e:
            print("添加一级评论报错信息", e)
            return jsonify(message="添加失败", code=400)
        return jsonify(message="添加成功", code=200)


# 七牛云上传
class QiniuToken(Resource):
    @login_required
    def get(self):
        token = qiniu_token()
        return jsonify(message="生成成功", code=200, data={"qiniu_token": token})


# 获取用户信息和修改
class UserResource(Resource):
    @login_required
    def get(self):
        uid = g.user_id
        user = UserModel.query.filter_by(uid=uid).first()
        return jsonify(message="获取用户信息成功", code=200, data=marshal(user, user_fields))

    def patch(self):
        uid = g.user_id
        parser = reqparse.RequestParser()
        parser.add_argument("name")
        parser.add_argument("profile_photo")
        args = parser.parse_args()
        name = args["name"]
        profile_photo = args["profile_photo"]
        print("前端获取到用户名", name)
        print("前端获取到头像地址", profile_photo)
        if name:
            UserModel.query.filter_by(uid=uid).update({"user_name": name})
            db.session.commit()
            return jsonify(message="修改名称成功", code=200)

        if profile_photo:
            UserModel.query.filter_by(uid=uid).update({"profile_photo": profile_photo})
            db.session.commit()
            return jsonify(message="修改头像成功", code=200)


api.add_resource(UserResource, "/user/profile")
api.add_resource(QiniuToken, "/qiniu")
api.add_resource(CommentFb, "/comment")
api.add_resource(CommentResource, "/comments")
api.add_resource(NewsXq, "/articles/<int:nid>")
api.add_resource(NewsResource, "/articles")
api.add_resource(ChannelResource, "/channels")
api.add_resource(SMSCode, "/sms_code")
api.add_resource(LoginResource, "/login")
